package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 网关拦截器
 * @author <a href="mailto:2891704036@qq.com">zhiyuheng</a>
 * @version 1.0
 * @description:
 * @date 2025/8/28 9:25
 */
@Component
public class AuthFilter implements GatewayFilter, Ordered {

    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取系统提供的白名单请求
        List<String> whites = ignoreWhiteConfig.getWhites();
        //获取当前请求的uri路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //判断当前请求是否是白名单请求
        if (StringUtils.matches(path,whites)){
            //如果是，放行
            return chain.filter(exchange);
        }
        //拦截验证token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        //非空校验
        if (StringUtils.isEmpty(token)){
            return GatewayUtils.errorResponse(exchange,"token为空");
        }
        //合法性验证
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange,"token不合法");
        }
        //有效性验证
        String userKey = JwtUtils.getUserKey(token);
        Boolean b = redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        if (!b){
            return GatewayUtils.errorResponse(exchange,"token已过期");
        }else {
            //续期
            redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY + userKey,30, TimeUnit.MINUTES);
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
